import React, { Component } from 'react'
import { Redirect, Route, RouteProps } from 'react-router-dom'
import { getToken } from 'utils/Storage'
import NotFound from 'pages/NotFound';

export default class index extends Component<RouteProps> {

  render() {
    const { component: Component, ...rest } = this.props as any
    return (
      <Route
        {...rest}
        render={(props) => {
          const token = getToken()
          const currentPath = props.location?.pathname
          if (token) {
            if (currentPath === '/404') { //登录了, 但被重定向到404, 显示404
              return <NotFound />
            }
            if (currentPath === '/login') { // 登录了, 但访问login, 重定向到首页
              return <Redirect to="/home" />
            }

            return <Component {...props} /> // 正常显示组件
          }
          else {
            return <Redirect to={{  // 未登录, 访问其他页面, 重定向到登录页, 并记录状态
              pathname: '/login',
              state: {
                fromPath: props!.location!.pathname,
              }
            }} />
          }
        }
        }
      />
    )
  }
}
